package MyTimer;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

public class MyTimer {
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    Object locker = new Object();

    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    MyTask task = queue.take();
                    long time = System.currentTimeMillis();
                    if (time >= task.getTime()) {
                        task.getRunnable().run();
                    } else {
                        queue.put(task);
                        long timedelay = task.getTime() - time;
                        synchronized (locker) {
                            locker.wait(timedelay);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();

        Thread threadDeamon = new Thread(() -> {
            try {
                while (true) {
                    TimeUnit.MICROSECONDS.sleep(100);
                    synchronized (locker) {
                        locker.notifyAll();
                    }

                }

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        threadDeamon.setDaemon(true);
        threadDeamon.start();
    }


    public void schedule(Runnable runnable, long time) {
        MyTask myTask = new MyTask(runnable, time);
        queue.put(myTask);
        synchronized (locker) {
            locker.notifyAll();
        }
    }
}


class MyTask implements Comparable {
    private Runnable runnable;
    private long time;

    public MyTask(Runnable runnable, long delay) {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不能为空");
        }
        if (delay < 0) {
            throw new IllegalArgumentException("时间不能为负数");
        }
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public int compareTo(Object o) {
        if (this.getTime() > getTime()) {
            return 1;
        } else if (this.getTime() < getTime()) {
            return -1;
        } else {
            return 0;
        }
    }
}
